package cn.edu.cupk.factory.method;

import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        try {
            List<String> classNames = ReadClassNamesFromXML();
            for (String className : classNames) {
                ICarFactory factory;
                // 反射机制
                Class classReflection = Class.forName(className);
                Object objectReflection = classReflection.newInstance();
                factory = (ICarFactory) objectReflection;
                Car car = factory.createCar();
                car.showInfo();
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }

    public static List<String> ReadClassNamesFromXML() {
        List<String> classNames = new ArrayList<>();
        try {
            // 读取XML文件
            DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = dFactory.newDocumentBuilder();
            Document doc = builder.parse(new File("src/config.xml"));
            // 获取包含类名的文本节点列表
            NodeList nl = doc.getElementsByTagName("className");
            for (int i = 0; i < nl.getLength(); i++) {
                Node classNode = nl.item(i).getFirstChild();
                classNames.add(classNode.getNodeValue());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return classNames;
    }
}
